//
//  KeyboardViewController.m
//  NetPhone
//
//  Created by intel intel on 12-4-25.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "KeyboardViewController.h"
#import "NetPhoneDAO.h"
#import "Contact.h"
#import "ContactCell.h"
#import "CallViewController.h"
#import "Common.h"
#import "ViewController.h"
#import "GlobalVar.h"
#import "BaifangViewController.h"
#import "UILabel+StringFrame.h"
#import "iToast.h"
#import "BannerView.h"
#import "EGOImageView.h"
#import "XMLReader.h"
#import "GDataXMLNode.h"

//
@implementation KeyboardViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        self.view.bounds=CGRectMake(0, -20, self.view.bounds.size.width, self.view.bounds.size.height);
    }
    UIImageView *bg1 = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voip_bg"]]autorelease];
    [self.view addSubview:bg1];
    headerView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, HEADER_HEIGHT)]autorelease];
    leftLabel = [[[UILabel alloc]initWithFrame:CGRectMake(2, 0, 158, HEADER_HEIGHT)]autorelease];
    leftLabel.font = [UIFont systemFontOfSize:14];
    leftLabel.textColor = [UIColor whiteColor];
    leftLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:leftLabel];
    rightLabel = [[[UILabel alloc]initWithFrame:CGRectMake(160, 0, 158, HEADER_HEIGHT)]autorelease];
    rightLabel.font = [UIFont systemFontOfSize:14];
    rightLabel.textColor = [UIColor whiteColor];
    rightLabel.text = @"正在查询...";
    rightLabel.textAlignment = UITextAlignmentRight;
    rightLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:rightLabel];
    [self.view addSubview:headerView];
    rows = [[NSMutableArray alloc]init];
    dataTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, HEADER_HEIGHT, 320, self.view.frame.size.height-52-49-222-10) style:UITableViewStylePlain];
    dataTableView.dataSource = self;
    dataTableView.delegate = self;
    dataTableView.backgroundColor = [UIColor colorWithRed:0.9f green:0.9f blue:0.9f alpha:1];
    dataTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:dataTableView];
    //
    callRecordViewController = [[CallRecordViewController alloc]init];
    callRecordViewController.style = 1;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        callRecordViewController.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height-49);
        callRecordViewController.dataTableView.frame = CGRectMake(0, 0, 320, self.view.frame.size.height-49-52-2*HEADER_HEIGHT);
    }else
    {
        callRecordViewController.view.frame = CGRectMake(0, HEADER_HEIGHT, 320, self.view.frame.size.height-49-HEADER_HEIGHT);
        callRecordViewController.dataTableView.frame = CGRectMake(0, 0, 320, self.view.frame.size.height-49-52-20);
    }
    [callRecordViewController reloadCallRecords];
    [self.view addSubview:callRecordViewController.view];
    keyboardView = [[[KeyboardView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-49-264, 320, 264)]autorelease];
    keyboardView.viewheight = self.view.frame.size.height-49;
    keyboardView.delegate = self;
    [self.view addSubview:keyboardView];
    [self createCallTab];
    leftLabel.text = @"在线";
    [self initComponent];
}
-(void)initComponent
{
    httpAgent=[[HttpForAgent alloc]init];
    httpAgent1=[[HttpForAgent alloc]init];
    httpAgent.delegate=self;
    httpAgent1.delegate=self;
    urlAddArr=[[NSMutableArray alloc]init];
    //#pragma mark请求拨号界面广告
    [httpAgent requestData:@"9" setUsername:GetAdv];
    //获取滚动字幕
    [self requestForScrollText];
    //[self scrollMsg:@"获取滚动字幕"];
}

#pragma 请求滚动字幕
-(void)requestForScrollText
{
    //滚动公告
    NSString* scrollSwitch=[[NSUserDefaults standardUserDefaults]objectForKey:@"showScrollOrNot"];
    int scrollSwtch=[scrollSwitch intValue];
    if (scrollSwtch==1)
    {
        [httpAgent1 requestData:@"4" setUsername:GetQueryPri];
    }
}

#pragma 拨号广告回调
-(void)requestAdvSuccess:(NSString *)str
{
    NSLog(@"===拨号广告回调=====%@",str);
    str=[str stringByReplacingOccurrencesOfString:@"&" withString:@"#+#"];
    NSError *parseError = nil;
    NSDictionary *nsDicData = [XMLReader dictionaryForXMLString:str error:&parseError];
    if (parseError)
    {
        NSLog(@"parseError=====%@",parseError.debugDescription);
        return;
    }
    NSDictionary *xmlDictionary = [[nsDicData valueForKey:@"Root"]valueForKey:@"ret"];
    NSString* code = [[xmlDictionary valueForKey:@"code"]valueForKey:@"text"];
    if([code isEqualToString:@"0"])
    {
        pageNum=[(NSString *)[[xmlDictionary valueForKey:@"adtotal"]valueForKey:@"text"]intValue];;
        if (pageNum>0)
        {
            NSUInteger height=IPHONE_H-264-49-HEADER_HEIGHT*2;
            if (bgView==nil)
            {
                bgView = [[ BannerView alloc]initWithFrame:CGRectMake(0, HEADER_HEIGHT, IPHONE_W,height)];
                bgView.delegate=self;
                [self.view addSubview:bgView];
            }
            NSMutableArray *nsMuArrImg = [[NSMutableArray alloc]initWithCapacity:5];
            for (int i=0; i<pageNum; i++)
            {
                NSString* urlId = [NSString stringWithFormat:@"url%d",i];
                NSString* nsStrUrl=[[xmlDictionary valueForKey:urlId]valueForKey:@"text"];
                NSArray* thearray=[nsStrUrl componentsSeparatedByString:@"@"];
                NSString* advStr=[thearray objectAtIndex:1];
                NSString* imUrl=[thearray objectAtIndex:3];
                imUrl = [imUrl stringByReplacingOccurrencesOfString:@"#+#" withString:@"&"];
                NSString* totalAdStr=[NSString stringWithFormat:@"%@%@",HTTP,advStr];
                [nsMuArrImg addObject:totalAdStr];
                //
                NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
                [defaults setObject:totalAdStr forKey:[NSString stringWithFormat:@"adStr%d",i]];
                [defaults setObject:imUrl forKey:[NSString stringWithFormat:@"urlAdd%d",i]];
                [defaults synchronize];
            }
            [bgView initData:nsMuArrImg imgBounds:CGRectMake(0, HEADER_HEIGHT, IPHONE_W,height)];
            [bgView start];
            [dataTableView setHidden:YES];
            [callRecordViewController.view setHidden:YES];
        }else
        {
            [callRecordViewController.view setHidden:NO];
        }

    }else
    {
        [callRecordViewController.view setHidden:NO];
    }

}


#pragma 滚动字幕回调
-(void)requestQueryPriSuccess:(NSString *)str
{
    //NSLog(@"the query str:%@",str);
    NSError *parseError = nil;
    NSDictionary *nsDicData = [XMLReader dictionaryForXMLString:str error:&parseError];
    if (parseError)
    {
        NSLog(@"parseError=====%@",parseError.debugDescription);
        return;
    }
    NSDictionary *xmlDictionary = [[nsDicData valueForKey:@"root"]valueForKey:@"ret"];
    NSString* code = [[xmlDictionary valueForKey:@"code"]valueForKey:@"text"];
    if([code isEqualToString:@"0"])
    {
        int count=[(NSString *)[[xmlDictionary valueForKey:@"adtotal"]valueForKey:@"text"]intValue];;
        NSMutableString* scrollStr=[[NSMutableString alloc]init];
        for (int i=0; i<count; i++)
        {
            NSString* urlId = [NSString stringWithFormat:@"url%d",i];
            NSString* nsStrInfo=[[xmlDictionary valueForKey:urlId]valueForKey:@"text"];;
            if (count>1)
            {
                nsStrInfo = [NSString stringWithFormat:@"%d.%@",i+1,nsStrInfo];
            }
            if (i==0)
            {
                [scrollStr appendString:[NSString stringWithFormat:@"%@",nsStrInfo]];
            }else
            {
                [scrollStr appendString:[NSString stringWithFormat:@"\t\t\t\t\t%@",nsStrInfo]];
            }
        }
        [self scrollMsg:scrollStr];
    }
}
-(void)queryMoney
{
    NSString *Account = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"LOGIN_USER_NUMBER"]];
    NSString *UserName = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"LOGIN_USER_KEY"]];
    NSString* _prMD5=[NSString stringWithFormat:@"%@%@%@",UserName,SOFT_ID,@"ysw"];
    NSString* MD5Str=[GlobalVar md5Str:_prMD5];
    startTime=[GlobalVar getTimeChuo];
    //
    ASIFormDataRequest* request;
    if ([GlobalVar sharedInstance].blnUseProxy==YES)
    {
        request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",origin_url_prefix,@"balance.php"]]];
        [request setProxyPort:ProxyPort];
        [request setProxyHost:[GlobalVar getTheBestIp]];//
    }else{
        request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[GlobalVar getTheBestUrl],@"proxy.php"]]];
        [request setPostValue:origin_url_prefix forKey:@"apiurl"];
        [request setPostValue:@"balance" forKey:@"act"];
    }
    [request setDelegate:self];
    [request setTimeOutSeconds:TIME_OUT_SECONDS];
    [request setPostValue:UserName forKey:@"mobile"];
    [request setPostValue:Account forKey:@"account"];
    [request setPostValue:SOFT_ID forKey:@"softid"];
    [request setPostValue:MD5Str forKey:@"md5"];
    [request setPostValue:MULTIAGENTSWITCH forKey:@"multiAgent"];
    [request setPostValue:NETWORKSTATE forKey:@"apn"];
    [request setPostValue:SOFT_VER forKey:@"version"];
    [request setDidFinishSelector:@selector(checkBalanceSuccess:)];
    [request setDidFailSelector:@selector(checkBalanceFail:)];
    [request setShouldAttemptPersistentConnection:NO];
    [request startAsynchronous];
}
//查询余额回调
-(void)checkBalanceSuccess:(ASIHTTPRequest*)request
{
    NSString* result=[request responseString];
    NSLog(@"查询余额结果:%@",result);
    endTime=[GlobalVar getTimeChuo];
    UInt64 time_cha=[GlobalVar preRequestTime:startTime AndAfterRequestTime:endTime];
    NSString* recod=[NSString stringWithFormat:@"\n%@|%d|%@|balance|%@|%@|%@|%llu \n",[GlobalVar getBundleIdentifierAndCurrentDate],[GlobalVar getCarrierNetWorkSignal],[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],SOFT_ID,[GlobalVar getNetWorkStates],[GlobalVar loginUserKey],time_cha];
    NSLog(@"查询余额写入记录:%@",recod);
    [GlobalVar writeTheInfoToTheLocal:recod];
    if ([result length]>0)
    {
      
        NSArray* arr=[result componentsSeparatedByString:@"|"];
        
        if ([arr count]==3 && [result rangeOfString:@"|"].location!=NSNotFound)
        {
            NSString* checkCode=arr[0];
            if ([checkCode isEqualToString:@"1"])
            {
                NSString* balance=arr[1];
                NSString* baoyueOrLiuliangCode=[[NSUserDefaults standardUserDefaults] objectForKey:@"baoyueOrLiuliang"];
                NSString* showMinCode=[[NSUserDefaults standardUserDefaults] objectForKey:@"showMin"];
                float balance_FloatValue=[balance floatValue];
                if ([balance length]>0)
                {
                    if ([baoyueOrLiuliangCode isEqualToString:@"0"])
                    {
                        if ([showMinCode isEqualToString:@"1"])
                        {
                            NSRange range = [balance rangeOfString:@"分钟"];
                            if (range.location!=NSNotFound)
                            {
                                [rightLabel setText:balance];
                            }else{
                                NSString* rate=[[NSUserDefaults standardUserDefaults] objectForKey:@"rate"];
                                float rate_FloatValue=[rate floatValue];
                                [rightLabel setText:[NSString stringWithFormat:@"%.2f分钟",balance_FloatValue/rate_FloatValue]];
                            }
                        }else
                        {
                            NSRange range1 = [balance rangeOfString:@"分钟"];
                            if (range1.location!=NSNotFound)
                            {
                                [rightLabel setText:balance];
                            }else{
                                [self showMoney:balance];
                            }
                            //[self showMoney:balance];
                            [self checkMoneyDate:arr[2]];
                        }
                    }else if ([baoyueOrLiuliangCode isEqualToString:@"1"])
                    {
                        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"CONTENT"] length]>0)
                        {
                            [rightLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"CONTENT"]];
                        }else
                        {
                            [rightLabel setText:@"包月"];
                        }
                    }else if (baoyueOrLiuliangCode==nil || [baoyueOrLiuliangCode isEqualToString:@""])
                    {
                        [self showMoney:balance];
                        [self checkMoneyDate:arr[2]];
                    }
                }else{
                    [rightLabel setText:@"查询失败!"];
                    
                }
            }else
            {
                [rightLabel setText:@"查询失败!"];
            }
        }
    }else
    {
        [GlobalVar writeTheInfoToTheLocal:@"收到数据包为空，重新选线路"];
        [[SocketDispatch sharedInstance] socketCheck];
        [GlobalVar alert:ERRORCODE];
    }
}
-(void)showMoney:(NSString*)money
{
    NSUserDefaults *standardUserDefaults=[NSUserDefaults standardUserDefaults];
    if ([money isEqualToString:@"-0"])
    {
        money=@"0";
    }
    [standardUserDefaults setObject:money forKey:@"money"];
    [standardUserDefaults synchronize];
    [rightLabel setText:[NSString stringWithFormat:@"余额:%@元",money]];
    
}
-(void)checkMoneyDate:(NSString*)dateStr
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSDate *d=[dateFormatter dateFromString:dateStr];
    NSString*timeString=[dateFormatter stringFromDate:[NSDate date]];
    NSDate *d2=[dateFormatter dateFromString:timeString];
    NSUserDefaults *standardUserDefaults=[NSUserDefaults standardUserDefaults];
    if (d2.timeIntervalSince1970>d.timeIntervalSince1970)
    {
        [standardUserDefaults setObject:@"1" forKey:@"moneyDate"];
    }else{
        [standardUserDefaults setObject:@"0" forKey:@"moneyDate"];
    }
    [standardUserDefaults synchronize];
}

-(void)checkBalanceFail:(ASIHTTPRequest*)request
{
    [[SocketDispatch sharedInstance] socketCheck];
    [GlobalVar alert:ERRORCODE];
    NSString* time_out_info=[NSString stringWithFormat:@"%@超时 %@",[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],[GlobalVar getBundleIdentifierAndCurrentDate]];
    [GlobalVar writeTheInfoToTheLocal:time_out_info];
}
-(void)scrollMsg:(NSString*)Str
{
    barnnerMsgView=[[ScrollMsgScrollView alloc]init];
    if (!barnnerMsgView.blnInitData)
    {
        CGRect barnnerMsgViewFrame=self.view.frame;
        barnnerMsgViewFrame.origin.x=35;
        barnnerMsgViewFrame.origin.y=-8;
        barnnerMsgViewFrame.size.height=30;
        barnnerMsgViewFrame.size.width=barnnerMsgViewFrame.size.width-115;
        barnnerMsgView.frame= barnnerMsgViewFrame;
        [barnnerMsgView setTextColor:[UIColor whiteColor]];
        [self.view addSubview:barnnerMsgView];
    }
    [barnnerMsgView initData:Str];
    [barnnerMsgView start];
}


-(void)createCallTab
{
    //NSLog(@"===createCallTab====");
    tabBarView=[[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-49, IPHONE_W, 49)];
    //
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        tabBarView.backgroundColor=[UIColor whiteColor];
    }else
    {
        tabBarView.backgroundColor=[UIColor darkGrayColor];
    }
    [tabBarView setHidden:YES];
    //tabBarView.userInteractionEnabled=YES;
    [[ViewController sharedInstance].view addSubview:tabBarView];
    //创建拔打按钮
    callButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [callButton setBackgroundImage:[UIImage imageNamed:@"callBtn"] forState:UIControlStateNormal];
    [callButton setBackgroundImage:[UIImage imageNamed:@"callBtn_Pressed"] forState:UIControlStateHighlighted];
    callButton.frame = CGRectMake(47, 0, 226, 49);
    callButton.titleLabel.font = [UIFont boldSystemFontOfSize:22];
    [callButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 50)];
    [callButton addTarget:self action:@selector(calling:) forControlEvents:UIControlEventTouchUpInside];
    [callButton setTitle:@"呼叫" forState:UIControlStateNormal];
    [callButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [tabBarView addSubview:callButton];
}

-(void)calling:(id)sender
{
    NSString* money=[[NSUserDefaults standardUserDefaults] objectForKey:@"money"];
    if (money && [money isEqualToString:@"0"])
    {
        iToast* toast=[iToast makeText:@"余额不足,请充值后再使用!"];
        [toast show];
        return;
    }
    NSString* moneyDate=[[NSUserDefaults standardUserDefaults] objectForKey:@"moneyDate"];
    if ([moneyDate isEqualToString:@"1"])
    {
        iToast* toast=[iToast makeText:@"余额已过期,请充值后再使用!"];
        [toast show];
        return;
    }
    NSString *value=[keyboardView.bgPhonePadEdit titleForState:UIControlStateNormal];
    value=[value stringByReplacingOccurrencesOfString:@"-" withString:@""];
    value=[value stringByReplacingOccurrencesOfString:@"+" withString:@""];
    value=[value stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self callWithNumber:value];
}
-(void)selectBannerImg:(NSString*)tagId
{
    NSString* urlStr=[NSString stringWithFormat:@"urlAdd%@",tagId];
    urlStr=[[NSUserDefaults standardUserDefaults]objectForKey:urlStr];
    //urlStr=@"http://baidu.com";
    //NSLog(@"返回回来的%@",urlStr);
    if ([urlStr isEqualToString:@""])
    {
        
    }else
    {
        BaifangViewController* baifang=[[BaifangViewController alloc]initWithUrl:urlStr];
        [self.navigationController pushViewController:baifang animated:NO];
        [baifang release];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"LOGIN_USER_NUMBER"])
    {
        [rightLabel setText:@""];
    }else{
        tongji=2;
        [NSThread detachNewThreadSelector:@selector(queryMoney) toTarget:self withObject:nil];
   }
    if (barnnerMsgView)
    {
        [barnnerMsgView start];
    }
    [keyboardView show];
    [self showImage];
    [self showTabbarAndhideCallButton];
    self.navigationController.navigationBarHidden=YES;
    [super viewWillAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated
{
    if (barnnerMsgView)
    {
        [barnnerMsgView stop];
    }
    [super viewDidDisappear:animated];
}
-(void)reloadCallRecords
{
    [callRecordViewController reloadCallRecords];
}

-(void)showKeyboard
{
    if (keyboardView.blnShowKeyboard==YES)
    {
        [keyboardView hide];
        [self hideImage];
    }else
    {
        [keyboardView show];
        [self showImage];
    }
}
-(void)keyboardValueChanged:(NSString *)value
{
   
    if (!value || [value isEqualToString:@""])
    {
        [rows removeAllObjects];
        if (!callRecordViewController.view.superview)
        {
            [self.view insertSubview:callRecordViewController.view aboveSubview:dataTableView];
        }
        
    }else{
        [rows removeAllObjects];
        NSArray *array1 = [[NetPhoneDAO sharedInstance]loadContactByCode:value equals:NO];
        [rows addObjectsFromArray:array1];
        if (callRecordViewController.view.superview)
        {
            [callRecordViewController.view removeFromSuperview];
        }
    }
    [dataTableView reloadData];
}


-(void)callWithNumber:(NSString *)value
{
    if (value && ![value isEqualToString:@""])
    {
        self.personPhone = value;
        NSArray *array1 = [[NetPhoneDAO sharedInstance]loadContactByCode:value equals:YES];
        if ([array1 count]>0) {
            Contact *contact = [rows objectAtIndex:0];
            self.userName = contact.name;
        }else{
            self.userName = value;
        }
        //
        [self showCallTypeView];
    }
}

-(void)showCallTypeView
{
    NSString* callway = [[NSUserDefaults standardUserDefaults]objectForKey:@"DirectDial"];
    if (callway&& [callway isEqualToString:@"1"])
    {
        UIActionSheet* callMethdSheet1=[[UIActionSheet alloc]initWithTitle:@"温馨提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"直拨" otherButtonTitles:@"回拨", nil];
        [callMethdSheet1 showInView:self.view];
    }else{
        ////拨打类型 0.直拨  1.回拨
        [Common callWithNumber:self.personPhone name:self.userName AndTheType:1];
    }
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex<=1)
    {
        if (self.userName && self.userName.length>0)
        {
            [Common callWithNumber:self.personPhone name:self.userName  AndTheType:buttonIndex];
        }else if (buttonIndex==1)
        {
            [Common callWithNumber:self.personPhone name:self.personPhone AndTheType:buttonIndex];
        }
    }
    
}
-(void)addNewPerson:(NSString *)value
{
	ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
	picker.newPersonViewDelegate = self;
	
    if (value && ![value isEqualToString:@""]) {
        ABRecordRef newPerson = ABPersonCreate();
        ABMutableMultiValueRef multiValue = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
        CFErrorRef error = NULL;
        multiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(multiValue, value, kABPersonPhoneMainLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiValue , &error);
        picker.displayedPerson = newPerson;
        CFRelease(multiValue);
        CFRelease(newPerson);
    }
    
    
	UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picker];
	[self presentModalViewController:navigation animated:YES];
	
	[picker release];
	[navigation release];
    
    
}

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
	[self dismissModalViewControllerAnimated:YES];
    
    [[ViewController sharedInstance]initNetPhoneData];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView 
{ 
	return 1; 
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 
{
    return [rows count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 39;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row=[indexPath row]; 
    Contact *contact = [rows objectAtIndex:row];
    static NSString *defaultCellIdentifier = @"defaultCellIdentifier";
    ContactCell *cell = (ContactCell *)[tableView dequeueReusableCellWithIdentifier:defaultCellIdentifier];
    if (cell == nil) {
        cell = [[[ContactCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:defaultCellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    [cell setContact:contact];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
	NSUInteger row=[indexPath row];
    Contact *contact = [rows objectAtIndex:row];
    self.personPhone = contact.phone;
    self.userName = contact.name;
    [self showCallTypeView];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)hideImage
{
    [self hideBanner:YES];;
}

-(void)showImage
{
    [self hideBanner:NO];
}
//隐藏bar广告
-(void)hideBanner:(BOOL)bln
{
    if (pageNum>0)
    {
        if (bgView.isHidden!=bln)
        {
            [bgView setHidden:bln];
        }
        [bgView pause:bln];
        if (dataTableView.isHidden==bln)
        {
            [dataTableView setHidden:(!bln)];
        }
        if (callRecordViewController.view.isHidden==bln)
        {
            [callRecordViewController.view setHidden:(!bln)];
        }
    }else{
        [callRecordViewController.view setHidden:NO];
    }
    
}

-(void)hideTabbarAndAddCallButton
{
   [tabBarView setHidden:NO];
}
-(void)showTabbarAndhideCallButton
{
   [tabBarView setHidden:YES];
}

-(void)dealloc
{
    [urlAddArr release];
    [httpAgent release];
    [httpAgent1 release];
    [tabBarView release];
    [array release];
    [callRecordViewController release];
    [rows release];
    [super dealloc];
}
@end
